<template>
	<div class="card art-custom-card" :style="{ height: containerMinHeight ,overflow:'hidden' }">
	  <div class="card-header" style="display: flex;justify-content: space-between;align-items: center;">
		  <div>
			  <i class="iconfont-sys">&#xe743;</i>
			  <span>元数据目录结构</span>
		  </div>
		  <div>
			<el-tooltip
			  effect="dark"
			  content="新建目录"
			>
			  <div class="btn" @click="showDialog('add',null)">
			    <i class="iconfont-sys">&#xe83e;</i>
			  </div>
			</el-tooltip>
		  </div>
	  </div>
	  <el-scrollbar style="height: calc(100% - 80px)" >
	  <div>
		  <el-tree
		    style="max-width: 600px"
		    :data="dataSource"
		    node-key="id"
		    default-expand-all
		    :expand-on-click-node="false"
			@node-click="handleNodeClick"
			:highlight-current="true"
		  >
		    <template #default="{ node, data }">
		      <div class="custom-tree-node">
		        <span>{{ node.label }}</span>
		        <div>
		          <el-button type="primary" link @click="showDialog('edit',data)">
		            编辑
		          </el-button>
		          <el-button
		            style="margin-left: 4px"
		            type="danger"
		            link
		            @click="deleteTree(node, data)"
		          >
		            删除
		          </el-button>
		        </div>
		      </div>
		    </template>
		  </el-tree>
	  </div>
	  </el-scrollbar>
	  
	  <ElDialog
	    v-model="dialogVisible"
	    :title="dialogType === 'add' ? '添加元数据目录' : '编辑元数据目录'"
	    width="30%"
	    align-center
		:draggable='true'
		:close-on-click-modal='false'
	  >
	    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="120px">
	      <ElFormItem label="目录名称" prop="name">
	        <ElInput v-model="formData.name" />
	      </ElFormItem>
	      <ElFormItem label="目录类型" prop="type">
	        <ElSelect v-model="formData.type">
			  <ElOption label="目录" value="folder" />
			  <ElOption label="表单" value="form" />
			  <ElOption label="表格" value="table" />
			  <ElOption label="查询" value="query" />
	        </ElSelect>
	      </ElFormItem>
			<ElFormItem label="目录序号" prop="sort" >
				<ElInputNumber
				  v-model="formData.sort"
				  :min="0"
				  :max="10"
				  controls-position="right"
				/>
			</ElFormItem>
	    </ElForm>
	    <template #footer>
	      <div class="dialog-footer">
	        <ElButton @click="dialogVisible = false">取消</ElButton>
	        <ElButton type="primary" @click="handleSubmit">提交</ElButton>
	      </div>
	    </template>
	  </ElDialog>
	</div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElDialog, FormInstance, ElTag } from 'element-plus'
import type { FormRules } from 'element-plus'
import { ElButton } from 'element-plus'
import type { RenderContentContext, RenderContentFunction } from 'element-plus'
import { useCommon } from '@/composables/useCommon'
const emits = defineEmits(['node-click'])
const { containerMinHeight } = useCommon()
const dialogType = ref('add')
const dialogVisible = ref(false)
const loading = ref(false)

interface Tree {
  id: number
  label: string
  type: string
  children?: Tree[]
}
type Node = RenderContentContext['node']
type Data = RenderContentContext['data']

// 表单实例
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
	id:'',
	name: '',
	type: '',
	sort:1
})

// 表单验证规则
const rules = reactive<FormRules>({
	name: [
		{ required: true, message: '请输入目录名称', trigger: 'blur' },
		{ min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
	],
	type: [
	  { required: true, message: '请输入目录类型', trigger: 'blur' },
	],
})

let id = 1000

const append = (data: Data) => {
  const newChild = { id: id++, label: 'testtest', children: [] }
  if (!data.children) {
    data.children = []
  }
  data.children.push(newChild)
  dataSource.value = [...dataSource.value]
}

// 删除目录
const deleteTree = (node: Node, data: Data) => {
	ElMessageBox.confirm('确定要删除该目录及其下包含的所有数据吗？', '删除目录', {
	  confirmButtonText: '确定',
	  cancelButtonText: '取消',
	  type: 'error'
	}).then(() => {
		remove(node,data);
		ElMessage.success('删除成功')
	})
}

const remove = (node: Node, data: Data) => {
  const parent = node.parent
  const children: Tree[] = parent.data.children || parent.data
  const index = children.findIndex((d) => d.id === data.id)
  children.splice(index, 1)
  dataSource.value = [...dataSource.value]
}

const renderContent: RenderContentFunction = (h, { node, data }) => {
  return h(
    'div',
    {
      class: 'custom-tree-node',
    },
    [
      h('span', null, node.label),
      h('div', null, [
        h(
          ElButton,
          {
            type: 'primary',
            link: true,
            onClick: () => append(data),
          },
          'Append '
        ),
        h(
          ElButton,
          {
            type: 'danger',
            link: true,
            style: 'margin-left: 4px',
            onClick: () => remove(node, data),
          },
          'Delete'
        ),
      ]),
    ]
  )
}

const dataSource = ref<Tree[]>([
  {
    id: 1,
    label: '日志管理',
	type:'folder',
    children: [
      {
        id: 4,
        label: '登录日志',
		type:'folder',
        children: [
          {
            id: 9,
            label: '登录列表',
			type:'table',
          },
          {
            id: 10,
            label: '登录列表查询条件',
			type:'query',
          },
        ],
      },
    ],
  },
])

const handleNodeClick=(data: Tree)=>{
  emits('node-click', data)
}


  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate((valid) => {
      if (valid) {
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        dialogVisible.value = false
      }
    })
  }
  
  
  // 显示对话框
  const showDialog = (type: string, row?: any) => {
    dialogVisible.value = true
    dialogType.value = type
  
    // 重置表单验证状态
    if (formRef.value) {
      formRef.value.resetFields()
    }
  
    if (type === 'edit' && row) {
  	  formData.id=row.id;
  	  formData.name=row.name;
  	  formData.type= row.type;
	  formData.sort= row.sort;
    } else {
  	  formData.id='';
  	  formData.name='';
  	  formData.type= '';
  	  formData.sort=1;
    }
  }


</script>

<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

	.btn {
	  width: 42px;
	  height: 42px;
	  line-height: 42px;
	  text-align: center;
	  cursor: pointer;
	  border-radius: 50%;
	  transition: background-color 0.2s ease;

	  &:hover {
		background-color: var(--art-gray-200);
	  }

	  i {
		font-size: 20px;
		color: var(--art-text-gray-700);
	  }
	}
</style>
